#!/bin/bash
# This script will install Oracle(Sun) Java 8 into an existing chroot
set -e

CHROOTDIR=$1
ARCH=$2

if [ ! -d "$CHROOTDIR" ]; then
    dj_make_chroot -d "$CHROOTDIR" -D Ubuntu -a "$ARCH"
fi

function cleanup {
    # Unmount things on cleanup
    umount -f "$CHROOTDIR/proc" >/dev/null 2>&1 || /bin/true
    umount -f "$CHROOTDIR/sys" >/dev/null 2>&1  || /bin/true
    umount -f "$CHROOTDIR/dev/pts" >/dev/null 2>&1  || /bin/true
}
trap cleanup EXIT

# A local caching proxy to use for debian packages
# (typically an install of aptcacher-ng), for example:
#DEBPROXY="http://aptcacher-ng.example.com:3142/"
[ -z "$DEBPROXY" ] && DEBPROXY=""

# To prevent (libc6) upgrade questions:
export DEBIAN_FRONTEND=noninteractive


mount -t proc proc "$CHROOTDIR/proc"
mount -t sysfs sysfs "$CHROOTDIR/sys"
# Required for some warning messages about writing to log files
mount --bind /dev/pts "$CHROOTDIR/dev/pts"

chroot "$CHROOTDIR" /bin/sh -c debconf-set-selections <<EOF
debconf shared/accepted-oracle-license-v1-1 select true
debconf shared/accepted-oracle-license-v1-1 seen true
EOF


PROXYSETTINGS="http_proxy=\"$DEBPROXY\" https_proxy=\"$DEBPROXY\""
chroot "$CHROOTDIR" /bin/sh -c "$PROXYSETTINGS apt-add-repository -y ppa:webupd8team/java"
chroot "$CHROOTDIR" /bin/sh -c "$PROXYSETTINGS apt-get update"
chroot "$CHROOTDIR" /bin/sh -c "$PROXYSETTINGS apt-get install oracle-java8-installer"

chroot "$CHROOTDIR" /bin/sh -c "apt-get autoremove --purge"
chroot "$CHROOTDIR" /bin/sh -c "apt-get clean"

umount "$CHROOTDIR/dev/pts"
umount "$CHROOTDIR/sys"
umount "$CHROOTDIR/proc"
